/* vim: set ts=2 et sw=2 cindent fo=qroca: */

package com.globant.google.mendoza.command;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.globant.google.mendoza.MendozaServer;
import com.globant.google.mendoza.MendozaRequest;
import com.globant.google.mendoza.MendozaServerState;

/** Represents the change merchant mendoza server command.
 */
public final class MendozaChangeMerchantCommand
extends MendozaBaseCommand {

  /** The class logger.
   */
  private static Log log =
    LogFactory.getLog(MendozaChangeMerchantCommand.class);

  /** Id label. */
  private final String idLabel = "Merchant Id";

  /** Key label. */
  private final String keyLabel = "Merchant key";

  /** Creates an instance of MendozaChangeMerchantCommand.
   *
   * @param mendozaRequest The mendoza server request.
   *
   * @param mendoza The mendoza server.
   *
   * @param mendozaState The mendoza server state.
   */
   public MendozaChangeMerchantCommand(
       final MendozaRequest mendozaRequest, final MendozaServer mendoza,
       final MendozaServerState mendozaState) {
     super(mendozaRequest, mendoza, mendozaState);
    setName("Change merchant");
  }

  /** Executes the mendoza server change merchant command.
   */
  public void execute() {
    log.trace("Entering execute");
    MendozaCommandResult result = new MendozaCommandResult();
    String commandResultMsg =
        "OK - Change merchant commmand sent to the mendoza server.";
    try {
      setRequestParameters();
      result.setSuccess(commandResultMsg);
    } catch (RuntimeException e) {
      commandResultMsg = e.getMessage();
      result.setError(commandResultMsg);
    }
    setResult(result);
    logCommand(this);
    log.trace("Leaving execute");
  }

  /** Sets the change merchant command parameters.
   */
  private void setRequestParameters() {
    log.trace("Entering setRequestParameters");
    String merchantId =
      getMendozaRequest().getRequestParameters().getProperty("id");
    String merchantKey =
      getMendozaRequest().getRequestParameters().getProperty("Key");
    if (merchantId == null) {
      log.trace("Leaving setRequestParameters");
      throw new RuntimeException("The merchant id cannot be null");
    }
    if (merchantKey == null) {
      log.trace("Leaving setRequestParameters");
      throw new RuntimeException("The merchant key cannot be null");
    }
    getMendozaState().setMerchantId(merchantId);
    getMendozaState().setMerchantKey(merchantKey);
    logRequestParameter(idLabel, merchantId);
    logRequestParameter(keyLabel, merchantKey);
    log.trace("Leaving setRequestParameters");
  }
}

